<?php
if((isset($_POST['paymethod'])))
	$ChosenMethod=$_POST['paymethod'];
session_start();
//require_once(".\classes\MySQL.php");
//$mysqlquery = new MySQL();

switch($ChosenMethod)
{
	case "Weekly":
		$item_amount = 40;
		$item_name = 'WorkerTrack Weekly Subscription';
		break;
	case "Monthly":
		$item_amount = 120;
		$item_name = 'WorkerTrack Monthly Subscription';
		break;	
	case "Yearly":
		$item_amount = 1200;
		$item_name = 'WorkerTrack Yearly Subscription';
		break;	
}		
// PayPal settings
//$paypal_email = 'brook_1332143376_biz@gmail.com';
$paypal_email = 'gadi_i_1337587648_biz@hotmail.com';
$return_url = 'http://localhost/HTML/PaymentSucceed.php';
$cancel_url = 'http://localhost/HTML/PaymentSucceed.php'; //temporary
$notify_url = 'http://localhost/PHP/paymentsPayPal.php';

//$item_name = 'WorkerTrack';
$item_number = 'CheckOut';
//$item_amount = $_SESSION['totalSum'];
$currency_code = 'USD';
//$_SESSION['payid'] = random_gen(25);

//while(!$mysqlquery->check_payId($_SESSION['payid']))
	//$_SESSION['payid'] = random_gen(25);

// Check if paypal request or response
if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){
	
	//add new order to the DB as 'new'
	//if(!isset($_SESSION['Shipment']))
//		$_SESSION['Shipment'] = 'pickup';
	
//	for($i=1 ; $i<=$_SESSION['views'] ; $i++ )
	//	$arrayOfPid[$i-1]=$_SESSION['Pid'][$i];
	//$i=1;
	//$result=$mysqlquery->getCartItems($arrayOfPid);
	//while($row = mysql_fetch_array($result))
	//{
		//$arrayOfQny[$i-1]=$_SESSION['Qnt'][$row['pid']];
		//$i++;
//	}

/*	if ($_SESSION['Shipment'] != 'pickup')
	{
		//shipping details
		$name = $_SESSION['shipname'];
		$address = $_SESSION['address'];
		$city = $_SESSION['city'];
		$country = $_SESSION['country'];
		$tel = $_SESSION['tel'];
		$zip = $_SESSION['zip'];
		//end of shipping details
		if ($sid = $mysqlquery->addShipment($name,$address,$city,$country,$tel,$zip))
		{
			$_SESSION['TrackNum']=$mysqlquery->addOrder($arrayOfPid,$arrayOfQny,$sid,$_SESSION['totalSum'],$_SESSION['payid'],'','','',$_SESSION['Shipment'],'new');
			$_SESSION['sid'] = $sid;
		}
	}*/
//	else $_SESSION['TrackNum']=$mysqlquery->addOrder($arrayOfPid,$arrayOfQny,0,$_SESSION['totalSum'],$_SESSION['payid'],'','','',$_SESSION['Shipment'],'new');
	
	// Append paypal account to querystring
	$querystring .= "?business=".urlencode($paypal_email)."&";	
	
	// Append amount& currency (£) to quersytring so it cannot be edited in html
	$querystring .= "cmd=".urlencode('_xclick')."&";
	$querystring .= "currency_code=".urlencode($currency_code)."&";
	$querystring .= "item_name=".urlencode($item_name)."&";
	$querystring .= "item_number=".urlencode($item_number)."&";
	$querystring .= "amount=".urlencode($item_amount)."&";
	
	// Append paypal return addresses
	$querystring .= "return=".urlencode(stripslashes($return_url))."&";
	$querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
	$querystring .= "notify_url=".urlencode($notify_url);
	
	// Append querystring with custom field
	//$querystring .= "&custom=".$_SESSION['payid'];
	
	// Redirect to paypal IPN
	header('location:https://www.sandbox.paypal.com/cgi-bin/webscr'.$querystring);
	exit();

}else{
session_start();
	// Response from Paypal

	// read the post from PayPal system and add 'cmd'
	$req = 'cmd=_notify-validate';
	foreach ($_POST as $key => $value) {
		$value = urlencode(stripslashes($value));
		$value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i','${1}%0D%0A${3}',$value);// IPN fix
		$req .= "&$key=$value";
	}
	
	// assign posted variables to local variables
	$data['item_name']			= $_POST['item_name'];
	$data['item_number'] 		= $_POST['item_number'];
	$data['payment_status'] 	= $_POST['payment_status'];
	$data['payment_amount'] 	= $_POST['mc_gross'];
	$data['payment_currency']	= $_POST['mc_currency'];
	$data['txn_id']				= $_POST['txn_id'];
	$data['receiver_email'] 	= $_POST['receiver_email'];
	$data['payer_email'] 		= $_POST['payer_email'];
	$data['custom'] 			= $_POST['custom'];
	$data['first_name']			= $_POST['first_name'];
	$data['last_name']			= $_POST['last_name'];
		
	// post back to PayPal system to validate
	$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
	$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
	$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
	
	$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);	
	
	if (!$fp) {
		// HTTP ERROR
	} else {	
		fputs ($fp, $header . $req);
		while (!feof($fp)) {
			$res = fgets ($fp, 1024);
			if (strcmp($res, "VERIFIED") == 0) {
				// Validate payment - we need to update accounts
				//$valid_PayId = $mysqlquery->check_payId($data['custom']);
			//	if($valid_PayId){				
				//	$orderid = $mysqlquery->updatePayments($data);	
					//$trackNum = $mysqlquery->updateOrder($data);
					
					//send email to client to notify payment received
					$to = $data['payer_email'];//'The email we inserted into paypal';
					$subject = 'ORDER DETAILS'; 
						
					$message = "This message was sent from:\n" .
							"	http://62.219.127.85/sites/webart/index.php\n" .
							"----------------------------------------------------------------------------------------------\n" .
							"	This is an order confirmation email, please don't reply\n" .
							"	Your order amount is ".$data['payment_amount']." $\n" .
							"	Your order tracking number is '".$trackNum."'\n" .
							"	You can track your order at http://62.219.127.85/sites/webart/index.php in 'track an order' menu\n" .
							"	Best Regards\n" .
							"-----------------------------------------------------------------------------------------------\n" ;
					$headers = 'From: worker.track@gmail.com' . "\r\n" .
						'Reply-To: worker.track@gmail.com' . "\r\n" .
						'X-Mailer: PHP/' . phpversion();

					mail($to, $subject, $message, $headers);
				//}						
			}		
		}		
	fclose ($fp);
	}	
}


function random_gen($length)
{
	$random= "";
	srand((double)microtime()*1000000);
	$char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	$char_list .= "abcdefghijklmnopqrstuvwxyz";
	$char_list .= "1234567890";

	for($i = 0; $i < $length; $i++)  
	{    
		$random .= substr($char_list,(rand()%(strlen($char_list))), 1);  
	}  
	return $random;
}
?>